import json
import cfg
from utils import ask
from utils.dingding import get_history_by_user_id,set_history_by_user_id
from utils.common import preprocess_question, get_base_info, intelligent_agent

import json
import flask
from flask import request
from flask import jsonify
app = flask.Flask(__name__)

@app.route('/chat', methods=['POST'])
def intelligent_agent_api():
    data = request.get_data()
    data = json.loads(data)
    user_id = data.get("user_id")
    question = data.get("question")
    history = get_history_by_user_id(user_id)
    base_info = get_base_info()
    raw_question = question
    question = preprocess_question(question,base_info,history=history)
    final_result = ask(question,history)
    new_history = history + [{"role": "user", "content": raw_question}] + [{"role": "assistant", "content": final_result[:200]}]
    if len(new_history) > 5:
        new_history = new_history[-5:]
    set_history_by_user_id(user_id,new_history)
    return jsonify({"message":final_result,"new_history":new_history})

@app.route('/get_info', methods=['post'])
def get_info():
    data = request.get_data()
    data = json.loads(data)
    user_id = data.get("user_id")
    question = data.get("question")
    history = get_history_by_user_id(user_id)
    base_info = get_base_info()
    question = preprocess_question(question,base_info,history=history)
    return jsonify({"message":question})

if __name__ == '__main__':
    # print(intelligent_agent('张龙前四天干啥了？'))
    # host 0.0.0.0 port cfg.port
    app.run(host='0.0.0.0', port=cfg.PORT)
